package com.magic0610.MagicYaml;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

import com.magic0610.MagicYaml.Exception.InternalLoadFailedException;
import com.magic0610.MagicYaml.Exception.MagicIOException;
import com.magic0610.MagicYaml.Exception.PathMismatchException;

/*
 * 包私有级内部方法类
 * 代码将会随时变动
 * 不提供技术支持
 */
class Functions {
    /*
     * 获取文件的jar内部路径
     * 抛出异常: PathMismatchException
     */
    static String getInternalPath(File origin, File dataFolder) {
        if (!isFilePathLegal(origin, dataFolder)) { //文件不合法返回null
            throw new PathMismatchException();
        }
        Path originPath = origin.toPath().toAbsolutePath();
        Path dataFolderPath = dataFolder.toPath().toAbsolutePath();

        String path = dataFolderPath.relativize(originPath).toString();
        //删除路径重合部分，得到jar核心中资源文件的内部路径

        path = path.replaceAll("\\\\", "/");
        //替换为内部路径使用的正斜杠
        //正则表达式中'\\\\'代表'\'
        if (!path.startsWith("/")) {
            path = "/" + path; //补全路径前方的正斜杠
        }
        return path;
    }

    /* 检查文件路径是否在数据文件夹下 */
    static boolean isFilePathLegal(File origin, File dataFolder) {
        return origin.toPath().toAbsolutePath().startsWith(dataFolder.toPath().toAbsolutePath());
    }

    /*
     * 一次性将路径中不存在的文件夹创建
     * 抛出异常: MagicIOException
     */
    static void createDirIfNotExist(Path path) {
        path = path.getParent();
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException exception) {
                throw new MagicIOException(exception);
            }
        }
    }
    static void createDirIfNotExist(File file) {
        createDirIfNotExist(file.toPath());
    }

    /*
     * 保存Jar内部配置到数据存储文件夹
     * 抛出异常: MagicIOException, InternalLoadFailedException
     */
    static void saveInternalFile(File file, String internalPath, boolean override) {
        try (InputStream fileStream = MagicYaml.class.getResourceAsStream(internalPath)) {
            if (fileStream == null) { //读取失败抛异常
                throw new InternalLoadFailedException(file.getName());
            }
            if (file.exists() && override) {
                file.delete(); //文件存在且开启覆盖时删除原文件
            }
            Files.copy(fileStream, file.toPath()); //复制文件
        } catch (IOException exception) {
            throw new MagicIOException(exception);
        }
    }
    static void saveInternalFile(YamlConfig yamlConfig, boolean override) {
        saveInternalFile(
            yamlConfig.getFile(), 
            yamlConfig.getInternalPath(), 
            override
        );
    }
}
